<template>
    <div>
        <div class="home">
            <div class="user-container">
                <div class="before-box"></div>
                <div class="user-box acea-row row-middle">
                    <img :src="userInfo.umAvatar" alt="ava" class="ava" v-if="isLogin">
                    <img :src="defaultUserHead" alt="default-ava" class="ava" v-else>
                    <div class="user-info" v-if="isLogin">
                        <div class="name">{{userInfo.umNickName}}</div>
                        <div class="info-box acea-row">
                            <div>{{userInfo.umMobile | plusxing(3,4)}}</div>
                            <div class="badge" @click="jumpPage('realNameOuth')" v-if="!userInfo.umName">未认证</div>
                            <div class="badge" v-else>已认证</div>
                        </div>
                    </div>
                    <div class="user-info" v-else @click="jumpPage1('wechatLogin')">
                        <div class="name">登录/注册</div>
                        <div class="info-box acea-row">
                            <div>请先登录..</div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="menu-box acea-row row-between">
                <Menu :icon="item.icon" :name="item.name" class="menu-item" v-for="item in menu" :key="item.id"
                      v-on:jump="jumpPage(item.url)"/>
            </div>
            <Overlay :show="show" z-index="3" :lock-scroll="false">
                <div class="wrapper acea-row row-middle row-center" @click="show = !show">
                    <div class="block" @click.stop>
                        <List
                                v-model="loading"
                                :finished="finished"
                                finished-text="没有更多了~"
                                :immediate-check="false"
                                @load="onLoad"
                        >
                            <div class="order-box" v-for="orderItem in orderList" :key="orderItem.smId"
                                 @click="onQRCODE(orderItem.smId)">
                                <div class="acea-row row-middle row-between">
                                    <div class="acea-row row-middle">
                                        <img :src="orderLeftIcon" alt="order-left-icon" class="order-left-icon">
                                        <div class="order-title">{{orderItem.smOrderName || orderItem.poPname}}</div>
                                    </div>
                                    <img :src="arrowRight" alt="arrow-right" class="arrow-right">
                                </div>
                                <div class="order-name">{{orderItem.smActivityName || orderItem.poSmActivityName}}</div>
                                <div class="acea-row row-middle row-between">
                                    <div class="order-time acea-row row-column row-column-between">
                                        <div>开始时间：{{orderItem.smActivityStartDate || orderItem.sm_activity_start_date |
                                            format}}
                                        </div>
                                        <div>结束时间：{{orderItem.smActivityEndDate || orderItem.smActivityEndDate |
                                            format}}
                                        </div>
                                    </div>
                                    <Button :icon="btnIcon" color="#FF8D51" class="bottom-btn" size="small"
                                            @click.stop="onBtn(orderItem.smId,userInfo.umId)"
                                            v-if="name === 1">抢单
                                    </Button>
                                    <Button color="#F7F8FC" class="bottom-btn pass-btn" size="small" :disabled="true"
                                            v-else>已抢单
                                    </Button>
                                </div>
                            </div>
                            <Empty description="暂无数据~" v-if="orderList.length === 0"/>
                        </List>
                    </div>
                    <Popup v-model="show1" get-container=".block" @close="onCloseQR">
                        <div v-if="show1" id="qrCode" ref="qrCodeDiv" v-html="config"></div>
                    </Popup>
                </div>
            </Overlay>
        </div>
    </div>
</template>

<script>
    import Menu from "../components/Menu";
    import {Overlay, Toast, List, Empty, Popup} from 'vant';
    import {mapGetters} from "vuex";
    import {oAuth} from "../libs/wechat";
    import {isWeixin, parseQuery} from "../utils";
    import localStorage from "@utils/store/localStorage";
    import {getShootList, orderInAccessAffirm} from "../api/public";
    import QRCode from 'qrcodejs2'
    import dayjs from "dayjs";
    import {getWechatConfig} from "@api/public";
    import {VUE_APP_WX_APP_ID} from "@utils/index";
    import {registerActivityLead} from "../api/user";

    // import VueQArt from 'vue-qart'
    const loadImg = name => require(`@/assets/images/${name}.png`)
    export default {
        name: 'Home',
        components: {
            Menu,
            Overlay,
            List,
            Empty,
            Popup,
        },
        data() {
            return {
                isLogin: false,
                defaultUserHead: loadImg('default_user_head'),
                menu: [
                    {
                        id: 1,
                        icon: loadImg('menu_icon1'),
                        name: '核销',
                        url: null
                    },
                    {
                        id: 2,
                        icon: loadImg('menu_icon2'),
                        name: '拍摄订单',
                        url: 'shootOrder'
                    },
                    // {
                    //     id: 3,
                    //     icon: loadImg('menu_icon3'),
                    //     name: '二维码',
                    //     url: null
                    // },
                    // {
                    //     id: 4,
                    //     icon: loadImg('menu_icon4'),
                    //     name: '余额',
                    //     url: 'balance'
                    // }
                ],
                show: false,
                loading: false,
                finished: false,
                orderLeftIcon: loadImg('order_left_icon'),
                arrowRight: loadImg('arrow-right'),
                btnIcon: loadImg('Lightning'),
                orderList: [],
                pageNo: 1,
                flag: false,
                show1: false,
                creationId: localStorage.get('creationId'),
                config: ''
            }
        },
        computed: {
            ...mapGetters(['userInfo'])
        },
        filters: {
            plusxing: function (str, frontLen, endLen) {
                let len = str.length - frontLen - endLen;
                let xing = '';
                for (let i = 0; i < len; i++) {
                    xing += '*';
                }
                return str.substring(0, frontLen) + xing + str.substring(str.length - endLen)
            },
            format: function (value) {
                if (!value) return ''
                return dayjs(value).format('YYYY-MM-DD HH:mm:ss')
            }
        },
        mounted() {
            this.init();
            getWechatConfig().then(res => {
                const config = Object.assign({}, res.data, {
                    appId: VUE_APP_WX_APP_ID
                });
                wx.config({...config, jsApiList: ["scanQRCode"]});
            });
        },
        methods: {
            init() {
                this.isLogin = !!this.userInfo.umId;
                if (this.isLogin) {
                    const {smId} = parseQuery();
                    registerActivityLead(smId,this.userInfo.umId).then(res => {
                        if (!res.code) {
                            Toast(res.msg)
                        }
                    })
                    this.defaultUserHead = this.userInfo.umAvatar;
                    localStorage.set('user', this.userInfo);
                }
            },
            init1(pageNo, pumId, poIsOver, searchCondition, poCreationId) {
                getShootList(pageNo, pumId, poIsOver, searchCondition, poCreationId).then(res => {
                    this.loading = true;
                    this.orderList.push.apply(this.orderList, res.data.records);
                    this.loading = false;
                    this.flag = res.data.records.length >= 10;
                })
            },
            jumpPage(page) {
                if (this.isLogin) {
                    if (!page) {
                        // this.show = true;
                        // this.pageNo = 1;
                        // this.orderList = [];
                        // this.init1(1, this.userInfo.umId, null, null, this.creationId);
                        const pumUid = this.userInfo.umId;
                        wx.scanQRCode({
                            needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
                            scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码，默认二者都有
                            success: function (res) {
                                const result = JSON.parse(res.resultStr); // 当needResult 为 1 时，扫码返回的结果
                                console.log(result)
                                // alert(result);
                                const creationId = localStorage.get('creationId');
                                if (result) return orderInAccessAffirm(result.orderId, result.userId, creationId, pumUid).then(res => {
                                    Toast(res.msg)
                                })
                            },
                            fail: function (err) {
                                alert(err)
                            }
                        });
                    } else {
                        this.$router.push(page)
                    }
                } else {
                    return Toast('请先登入！')
                }
            },
            jumpPage1() {
                if (isWeixin()) {
                    oAuth();
                }
            },
            onLoad() {
                if (this.flag) {
                    this.pageNo++;
                    this.init1(this.pageNo, this.userInfo.umId, null, this.searchValue, this.creationId)
                } else {
                    this.finished = true;
                }
            },
            onQRCODE(id) {
                this.show1 = !this.show1;
                this.$nextTick(() => {
                    new QRCode(this.$refs.qrCodeDiv, {
                        text: `orderId=${id},userId=${this.userInfo.umId}`,
                        width: 200,
                        height: 200,
                        colorDark: "#000000",
                        colorLight: "#ffffff",
                        correctLevel: QRCode.CorrectLevel.L
                    })
                    this.$once('hook:beforeDestroy', function () {
                        this.config = ''
                    })
                })
            },
            onCloseQR() {
                console.log('close')
                this.config = ''
            }
        }
    }
</script>
<style scoped lang="scss">
    .home {
        .user-container {
            height: 210px;
            background-color: #0DCDB5;

            .before-box {
                height: 38px;

            }

            .user-box {
                height: 110px;
                padding: 0 25px;

                .ava {
                    height: 78px;
                    width: 78px;
                    border-radius: 50%;
                    margin-right: 20px;
                    display: block;
                }

                .user-info {
                    color: #ffffff;

                    .name {
                        font-size: 32px;
                        font-weight: 500;
                    }

                    .info-box {
                        font-size: 16px;
                        font-weight: 400;
                        margin-top: 10px;

                        .badge {
                            display: inline-block;
                            border-radius: 4px;
                            background-color: #FF8D51;
                            padding: 2px 5px;
                            font-size: 12px;
                            margin-left: 10px;
                        }
                    }
                }
            }
        }

        .menu-box {
            position: absolute;
            top: 223px;
            z-index: 2;
            width: 100%;
            padding: 0 15px;

            .menu-item:nth-child(3) {
                margin-top: 15px;
            }

            .menu-item:nth-child(4) {
                margin-top: 15px;
            }
        }

        .wrapper {
            height: 100%;

            .block {
                width: 360px;
                height: 300px;
                background: rgba(255, 255, 255, 1);
                border-radius: 11px;
                overflow-y: scroll;

                .order-box {
                    margin: 15px auto;
                    width: 355px;
                    /*width: 80%;*/
                    height: 150px;
                    background: rgba(255, 255, 255, 1);
                    border-radius: 8px;
                    padding: 20px;

                    .order-left-icon {
                        width: 15px;
                        height: 15px;
                    }

                    .order-title {
                        font-size: 14px;
                        font-weight: 400;
                        color: rgba(66, 69, 95, 1);
                        margin-left: 9px;
                    }

                    .arrow-right {
                        width: 14px;
                        height: 14px;
                    }

                    .order-name {
                        font-size: 18px;
                        font-weight: 500;
                        color: rgba(66, 69, 95, 1);
                        margin: 17px 0 10px;
                    }

                    .order-time {
                        font-size: 12px;
                        font-weight: 400;
                        color: rgba(163, 165, 177, 1);
                        height: 40px;
                    }

                    .bottom-btn {
                        width: 70px;
                        height: 30px;
                        border-radius: 4px;
                        font-size: 14px;
                        font-weight: 400;
                    }

                    .pass-btn {
                        color: #A3A5B1 !important;
                    }
                }
            }
        }
    }

</style>
